package com.eazyshop.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

/**
 * 网关IP过滤器
 */
@Component
public class IpFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获得请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获得远程地址
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        // 获得IP地址
        String hostName = remoteAddress.getHostName();
        System.out.println("访问IP地址是："+hostName);
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 定义全局过滤器的优先级别
     * 数字越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
